package com.lzy.okgo.harmony.ui.slice;

import com.lzy.okgo.harmony.ResourceTable;
import com.lzy.okgo.harmony.http.WanRequester;
import com.lzy.okgo.harmony.model.HomeArticleModel;
import com.lzy.okgo.harmony.model.base.HttpModel;
import com.lzy.okgo.harmony.model.base.PageModel;
import com.lzy.okgo.harmony.ui.itemprovider.HomeArticleItemProvider;
import com.lzy.okgo.harmony.util.ToastUtil;
import com.lzy.okgo.harmony.util.rx.RxLifecycleUtil;
import com.lzy.okgo.harmony.util.rx.RxSchedulerUtil;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.ListContainer;
import ohos.utils.net.Uri;

import java.util.ArrayList;
import java.util.List;

/**
 * 首页
 */
public class HomeSlice extends AbilitySlice {
    private static final String TAG = HomeSlice.class.getSimpleName();

    public static HomeSlice newInstance() {
        return new HomeSlice();
    }

    private ListContainer vList;
    private final List<HomeArticleModel> mListData = new ArrayList<>();
    private final HomeArticleItemProvider mListItemProvider = new HomeArticleItemProvider(mListData);

    /**
     * 当前页码
     */
    private int mCurrentPage;
    /**
     * 是否有下一页
     */
    private boolean hasMore = true;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_slice_home);
        findView();
        bindView();
        setData();
    }

    private void findView() {
        vList = (ListContainer) findComponentById(ResourceTable.Id_list);
    }

    private void bindView() {
        //设置适配器
        vList.setItemProvider(mListItemProvider);
        //设置点击事件
        vList.setItemClickedListener(new ListContainer.ItemClickedListener() {
            @Override
            public void onItemClicked(ListContainer listContainer, Component component, int position, long id) {
                HomeArticleModel itemModel = mListData.get(position);
                String link = itemModel.getLink();
                //点击跳转到浏览器
                Intent intent = new Intent();
                Operation operation = new Intent.OperationBuilder()
                        .withUri(Uri.parse(link))
                        .build();
                intent.setOperation(operation);
                startAbility(intent);
            }
        });
        //设置滚动监听，滚动结束后回调
        vList.setScrollListener(new ListContainer.ScrollListener() {
            @Override
            public void onScrollFinished() {
                //没有下一页
                if (!hasMore) {
                    return;
                }
                int lastVisibleItemPosition = vList.getLastVisibleItemPosition();
                if (lastVisibleItemPosition == mListData.size() - 1) {
                    //加载更多
                    loadMore();
                }
            }
        });
    }

    private void setData() {
        refresh();
    }

    private void refresh() {
        this.mCurrentPage = 0;
        getWxArticle(mCurrentPage, true);
    }

    private void loadMore() {
        int nextPage = this.mCurrentPage + 1;
        getWxArticle(nextPage, false);
    }

    /**
     * 获取公众号列表
     */
    private void getWxArticle(int page, boolean isRefresh) {
        WanRequester.getHomeArticle(TAG, page)
                //IO切换到主线程
                .compose(RxSchedulerUtil.ioToMain())
                //生命周期绑定
                .as(RxLifecycleUtil.bindLifecycle(getLifecycle()))
                .subscribe(new Consumer<HttpModel<PageModel<HomeArticleModel>>>() {
                    @Override
                    public void accept(@NonNull HttpModel<PageModel<HomeArticleModel>> model) throws Exception {
                        PageModel<HomeArticleModel> pageModel = model.getData();
                        if (pageModel == null) {
                            return;
                        }
                        List<HomeArticleModel> list;
                        if (pageModel.getDatas() != null) {
                            list = pageModel.getDatas();
                        } else {
                            list = new ArrayList<>();
                        }
                        //是否有下一页
                        hasMore = !pageModel.isOver();
                        //更新当前页码
                        mCurrentPage = pageModel.getOffset();
                        if (isRefresh) {
                            mListData.clear();
                        }
                        //更新列表
                        mListData.addAll(list);
                        mListItemProvider.notifyDataChanged();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@NonNull Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                        ToastUtil.toast(getContext(), "请求失败：" + throwable.getMessage());
                    }
                });
    }
}